﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IResetable
{
    void OnReset();
}
public class GameObjectPool : MonoBehaviour
{
    public static GameObjectPool instance;
    private void Awake()
    {
        if (GameObjectPool .instance!= null)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
    }
    private Dictionary<string, List<GameObject>> cache = new Dictionary<string, List<GameObject>>();

    public GameObject CreateObject(string key, GameObject prefab, Vector3 position, Quaternion rotation, Action<GameObject> action = null)
    {
        GameObject go = FindUsableObject(key);
        if (go == null)
        {
            go = AddObject(key, prefab);
        }
        if (action != null)
        {
            action(go);
        }
        UseObject(position, rotation, go);
        return go;
    }
    //发现可使用的对象
    private GameObject FindUsableObject(string key)
    {
        if (cache.ContainsKey(key))
            return cache[key].Find(g => !g.activeInHierarchy);
        return null;
    }
    //添加对象
    private GameObject AddObject(string key, GameObject prefab)
    {
        GameObject go = Instantiate(prefab);
        GameObject.DontDestroyOnLoad(go);
        if (!cache.ContainsKey(key))
            cache.Add(key, new List<GameObject>());
        cache[key].Add(go);
        return go;
    }
    private void UseObject(Vector3 position, Quaternion rotation, GameObject go)
    {
        go.transform.position = position;
        go.transform.rotation = rotation;
        go.SetActive(true);
        foreach (var i in go.GetComponents<IResetable>())
        {
            i.OnReset();
        }
    }
    //回收对象
    public void CollectObject(GameObject go, float delay = 0)
    {
        StartCoroutine(CollectObjectDelay(go, delay));
    }
    private IEnumerator CollectObjectDelay(GameObject go, float delay)
    {
        yield return new WaitForSeconds(delay);
        go.SetActive(false);
    }
    //清空一个Key，和其对象
    public void Clear(string key)
    {
        for (int i = cache[key].Count - 1; i >= 0; i--)
        {
            Destroy(cache[key][i]);
        }
        cache.Remove(key);
    }
    public void ClearAll()
    {
        foreach (var key in new List<string>(cache.Keys))
        {
            Clear(key);
        }
    }
}
